package com.dries.security.browser.controller;

import cn.hutool.core.util.StrUtil;
import com.dries.security.common.api.CommonResult;
import com.dries.security.core.properties.SecurityCoreConstants;
import com.dries.security.core.properties.SecurityCoreProperties;
import com.dries.security.core.social.SocialController;
import com.dries.security.core.social.SocialUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/3 14:49
 */
@Slf4j
@RestController
public class BrowserSecurityController extends SocialController {

    @Resource
    private SecurityCoreProperties coreProperties;
    @Resource
    private ProviderSignInUtils providerSignInUtils;

    // 缓存请求
    private final RequestCache requestCache = new HttpSessionRequestCache();
    // 请求跳转
    private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    /**
     * 当需要身份认证时，跳转到这里
     * @param req
     * @param resp
     * @return
     */
    @GetMapping(SecurityCoreConstants.DEFAULT_UNAUTHENTICATION_URL)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public CommonResult requireAuthentication(HttpServletRequest req, HttpServletResponse resp){

        SavedRequest request = requestCache.getRequest(req, resp);
        if (request != null) {
            String redirectUrl = request.getRedirectUrl();
            log.info("引发跳转的请求是： " + redirectUrl);
            if (StrUtil.endWithIgnoreCase(redirectUrl, ".html")){
                try {
                    redirectStrategy.sendRedirect(req,resp, coreProperties.getBrowser().getLoginPage());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return CommonResult.unauthorized();
    }

    /**
     *  用户第一次社交登录时，会引导用户进行用户注册或绑定，此服务用于在注册或绑定页面获取社交网站用户信息
     * @param request
     * @return
     */
    @GetMapping(SecurityCoreConstants.DEFAULT_SOCIAL_USER)
    public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        return buildSocialUserInfo(connection);
    }

    @GetMapping(SecurityCoreConstants.DEFAULT_SESSION_INVALID)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public CommonResult sessionInvalid() {
        return CommonResult.failed("session失效");
    }

}
